package com.szosen.measurement;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.szosen.database.DBService;
import com.szosen.database.HealthRecord;
import com.szosen.database.xindian;
import com.szosen.device.jianhuyi.BeneCheckDeviceHB;
import com.szosen.jkzj.R;
import com.szosen.jkzj.activity.BaseActivity;
import com.szosen.jkzj.util.Contants;
import com.szosen.util.BackGroundThread;
import com.szosen.util.BackGroundThread.BackGroundTask;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.FileSaveUtilecg2;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.StringUtils;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;
//import com.health.database.DatabaseService;
//import com.health.database.MYECGTable;
//import com.health.database.Tables;
//import com.health.model.DBService;
//import com.health.util.MyMD5;
//import com.health.util.MyProgressDialog;

public class MeasureECGActivity extends Activity {
    public static final String FileName = "村医版";
    private Button startBtn;
    private Button uploadBtn;
    private TextView connectTV;
    // private Button searchBtn;
    private SurfaceView sfv;
    private Context context;
    private OnClickListener clickListener;
    public ImageView iv_xinlvicon = null;
    private Handler handler;
    static EditText et_xinlv = null;
    private static String token = null;
    private ControlView clv = null;
    public static final int UPLOAD_RESULT = 0x10040;
    public static final int OFFLINE_RESULT = 0x10041;
    public static final int OFFLINE_OK = 0x10042;
    public static final int OFFLINE_ERROR = 0x10043;
    public static final int OFFLINE_RESULT_OK = 0x10048;
    public static final int OFFLINE_RESULT_ERROR = 0x10049;
    private String startCheckTime = "";
    private String endCheckTime = "";
    private static final String ACTION_USB_PERMISSION = "com.wch.wchusbdriver.USB_PERMISSION";
    protected final Object ThreadLock = new Object();
    private static final int READER_DATA = 3;
    byte[] readBuffer;
    public boolean isConfiged = false;
    private UsbManager myManager;
    private ECGDevice ecgDevice;
    UsbEndpoint mBulkInPoint;
    UsbDeviceConnection mDeviceConnection;
    ArrayList<int[]> ecgData;
    private UploadECGBean bean;
    /**
     * 已经开始了吗？ false还没开始，true已经开始
     */
    private boolean isStarted = false;
    // "http://101.200.199.120:22080/ECGAPIServer/remoteAPI";
    // 读取数据（从硬件设备中）
    // 判断是否支持USB
    private TreeMap<String, Integer> report1;

    private void UsbSupported() {
        if (ecgDevice != null) {
            ecgDevice.CloseDevice();
            ecgDevice = null;
        }
        // myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        ecgDevice = new ECGDevice(myManager, this, ACTION_USB_PERMISSION,
                usbHandler);
        ecgDevice.setOnGetDataListener(new ECGDevice.GetDataListener() {
            byte[] ecgBytes = new byte[373142 + 100];
            byte[] ecgBytesNow = new byte[2048 * 1000];
            int index = 0;
            boolean isGetData = false;
            int count = 0;
            boolean isGetDataNow = false;
            int indexNow = 0;
            private int datalength = 0;

            @SuppressLint("NewApi")
            @Override
            public void getData(byte[] data, int length) {
                count += length;
                byte[] temp = new byte[length];
                for (int i = 0; i < length; i++) {
                    temp[i] = data[i];
                }
                // System.out.println("线程获取到数据："+StringUtils.ByteArrToHex(temp));
                if (length >= 2) {
                    if (temp[0] == (byte) -1 && temp[1] == (byte) 0
                            && temp[2] == (byte) -69 && temp[3] == (byte) 68) {
                        isGetData = true;
                    }
                    if (isGetData) {
                        for (int i = 0; i < length; i++) {
                            if (i + 1 < length && data[i] == (byte) 49
                                    && data[i + 1] == (byte) 96) {
                                i++;
                                continue;
                            }
                            ecgBytes[index] = data[i];
                            index++;
                        }
                        if (index == 273142) {
                            byte[] b = new byte[273142];
                            System.arraycopy(ecgBytes, 0, b, 0, index);
                            bean = new UploadECGBean(b);
                            // 获取到12导的数据。
                            ecgData = bean.getECG12();
                            clv.drawFlag = false;
                            // clv.setResultConfig();
                            // clv.setEcgData(ecgData);
                            ArrayList<int[]> rr = UploadECGBean
                                    .getMeiGeShuArray(ecgData, 8);
                            // clv.cleanAllShowData();
                            clv.addResultECGData(rr);
                            StringBuilder sb = new StringBuilder();
                            report1 = bean.getReport1();
                            Set entries = report1.entrySet();
                            if (entries != null) {
                                sb.append("心率                     :"
                                        + report1.get("心率") + " bpm" + "\n");
                                sb.append("PR_间期            :"
                                        + report1.get("PR_间期") / 10 + " ms"
                                        + "\n");
                                sb.append("QRS_时限         :"
                                        + report1.get("QRS_时限") / 10 + " ms"
                                        + "\n");
                                sb.append("QT/QTC间期    :"
                                        + report1.get("QT_间期") / 10 + "/"
                                        + report1.get("QTC_间期") / 10 + " ms"
                                        + "\n");
                                sb.append("P/QRS/T电轴 :" + report1.get("P_电轴")
                                        / 10 + "/" + report1.get("QRS_电轴") / 10
                                        + "/" + report1.get("T_电轴") / 10 + " °"
                                        + "\n");
                                sb.append("RV5/SV1电压 :"
                                        + (float) report1.get("RV5_电压") / 100
                                        + "/" + (float) report1.get("SV1_电压")
                                        / 100 + " mV" + "\n");
                                // }
                                // System.out.println("bean的12心电报告：key=" +
                                // key
                                // + ",value" + value);
                                // }
                            }
                            // 按回车切割。获取结论字符数组
                            String[] results = bean.getReport2().split("\n");
                            // 结论2个数大于1，并且没有正常心电图
                            if (results.length > 1) {
                                String lastStr = results[results.length - 1];
                                if (!lastStr.contains("正常心电图")) {
                                    results[results.length - 1] = "";
                                }
                            }
                            StringBuilder result_Strs = new StringBuilder();
                            for (int i = 0; i < results.length; i++) {
                                result_Strs.append(results[i]);
                                result_Strs.append("\n");
                            }
                            sb.append("结论：" + result_Strs.toString());

                            HealthRecord hr = BaseActivity.getHealthRecord();
                            String name = BaseActivity.getName();
                            String idCard = BaseActivity.getIdCard();
                            String sexCode = hr.getSexCode();
                            String sex = "";
                            if (sexCode.equals("1")) {
                                sex = "男";
                            } else if (sexCode.equals("2")) {
                                sex = "女";
                            }
                            int yearsOld = Tools.getYearoldByIdcard(idCard);
                            String age = yearsOld == 0 ? "" : yearsOld + "";
                            // 医院姓名暂时没保存。。。不知道存什么进去。
                            String hospitalName = SharedpreferenceUtil
                                    .getHospitalName(context, "");
                            boolean printResult = false;
                            FileSaveUtilecg2.saveEcgPNG(pngPath, pngFileName,
                                    bean.getReport1IntArray(), name, sex,
                                    idCard, age, time, result_Strs.toString(),
                                    hospitalName,
                                    UploadECGBean.getMeiGeShuArray(ecgData, 4), printResult);
                            updateUiHandler.obtainMessage(updateMeasureOK,
                                    sb.toString()).sendToTarget();
                            updateUiHandler.obtainMessage(updateTVXinLv,
                                    bean.getXinLv()).sendToTarget();
                            // System.out.println("ecgData是：" + ecgData);
                            isGetData = false;
                        }
                    }
                    // System.out.println("Measure中的数据count是：" + count
                    // + ",index是：" + index);
                }
                // System.out.println("在线程获取到数据了。。。"
                // + StringUtils.ByteArrToHex(temp) + "总数" + count
                // + ",index=" + index);
                if (StringUtils.ByteArrToHex(temp)
                        .contains("CC 33 AA 55 0D 0A")) {
                    // 测量数据完成
                    ecgDevice.isStop = true;
                    // isGetData = false;
                    // Toast.makeText(context, "心电数据保存完成。。。", 0).show();
                    // System.out.println("心电数据保存完成，ecg的长度：" + index);
                }
            }

            @Override
            public void getInpointAndConnect(UsbEndpoint point,
                                             UsbDeviceConnection conn) {
                mBulkInPoint = point;
                mDeviceConnection = conn;
            }

            @Override
            public void getData2(byte[] data, int length) {
                byte[] temp = new byte[length];
                System.arraycopy(data, 0, temp, 0, length);
                ControlView.ecgBytesQueue.offer(temp);
                // System.out.println("执行的是getdata2，就是实时的数据显示");
            }
        });
        if (!ecgDevice.UsbFeatureSupported())// 判断系统是否支持USB HOST
        {
            Dialog dialog = new AlertDialog.Builder(MeasureECGActivity.this)
                    .setTitle("提示")
                    .setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }

    /**
     * 打开百捷
     */
    private void OpenBeneCheck() {
        UsbSupported();
        boolean flags;
        if (false == isConfiged) {
            if (ecgDevice.isConnected()) {
                flags = ecgDevice.UartInit();
                return;
            } else {
                openDevice();
                setConfig();
                // 读取数据
            }
        }
    }

    public static final int updateTVXinLv = 111;
    public static final int updateMeasureOK = 112;
    public static final int uploadOK = 113;
    public static final int updateEcgXinLvNow = 114;
    public static final int updateCloseDevice = 116;
    // 是否完成心电测量。
    boolean measureECGOK = false;
    public Handler updateUiHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BeneCheckDeviceHB.WHAT_RECEIVE_TIMEOUT:
                    Toast.makeText(context, "usb接收命令数据超时，请检查设备是否故障！", Toast.LENGTH_SHORT).show();
                    break;
                case updateTVXinLv:
                    String xinlv = (String) msg.obj;
                    et_xinlv.setText(xinlv);
                    break;
                case updateMeasureOK:
                    isStarted = false;
                    mMeasureDialog.dismiss();
                    endCheckTime = Tools.GetCurrentTime();
                    // 关闭设备。
                    ecgDevice.CloseDevice();
                    ecgDevice.isStop = true;
                    startBtn.setEnabled(false);
                    String ecgMeasureResult = (String) msg.obj;
                    AlertDialog.Builder bb = new AlertDialog.Builder(context)
                            .setNegativeButton("确定",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            dialog.cancel();
                                        }
                                    });

                    AlertDialog resultDialog = showDialog("结论：", ecgMeasureResult,
                            true);
                    resultDialog.show();
                    measureECGOK = true;
                    rhythm = "" + ecgMeasureResult;
                    uploadBtn.setEnabled(true);
                    clv.stop();
                    // uploadECGMeasureData();
                    break;
                case uploadOK:
                    iv_xinlvicon.setImageResource(R.drawable.light_greed);
                    break;
                case updateEcgXinLvNow:
                    // clv.addECGDdataNow(((OneECG) msg.obj).getECG12());
                    et_xinlv.setText((String) msg.obj);
                    break;
                case updateCloseDevice:
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public void openDevice() {
        UsbDevice device = ecgDevice.EnumerateDevice();
        if (device == null) {
            usbHandler.obtainMessage(MeasureECGActivity.WHAT_NOFOUNDDEVICE)
                    .sendToTarget();
        } else {
            ecgDevice.OpenDevice(device);
            usbHandler.obtainMessage(MeasureECGActivity.WHAT_OPENDEVICESUCCESS)
                    .sendToTarget();
        }
    }

    public void setConfig() {
        if (ecgDevice != null && ecgDevice.getUsbDevice() != null) {
            if (ecgDevice.SetConfig(500000, (byte) 8, (byte) 1, (byte) 0,
                    (byte) 0)) {
                usbHandler.obtainMessage(MeasureECGActivity.WHAT_CONFIGSUCCESS)
                        .sendToTarget();
            } else {
                usbHandler.obtainMessage(MeasureECGActivity.WHAT_CONFIGFAILED)
                        .sendToTarget();
            }
        }
    }

    public final static int WHAT_CONFIGFAILED = 1;
    public final static int WHAT_CONFIGSUCCESS = 2;
    public final static int WHAT_NOFOUNDDEVICE = 4;
    public final static int WHAT_OPENDEVICESUCCESS = 5;
    public Handler usbHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case ECGDevice.WHAT_ATTACHED:
                    Toast.makeText(MeasureECGActivity.this, "设备串口已插入!",
                            Toast.LENGTH_SHORT).show();
                    sendStartNowCmd();
                    break;
                case ECGDevice.WHAT_DISCONNECTED:
                    Toast.makeText(MeasureECGActivity.this, "设备串口已断开!",
                            Toast.LENGTH_SHORT).show();
                    connectTV.setText("设备已断开");
                    connectTV.setTextColor(Color.RED);
                    closeAllECG();
                    break;
                case WHAT_CONFIGFAILED:
                    Toast.makeText(MeasureECGActivity.this, "设备串口打开失败!",
                            Toast.LENGTH_SHORT).show();
                    break;
                case ECGDevice.WHAT_CONN_SUCCEED:
                    Toast.makeText(MeasureECGActivity.this, "设备串口打开成功!",
                            Toast.LENGTH_SHORT).show();
                    sendStartNowCmd();
                    if (isStarted) {
                        ecgDevice.isNow = false;
                        if (mMeasureDialog != null && !mMeasureDialog.isShowing()) {
                            mMeasureDialog.show();
                        } else {
                            mMeasureDialog = showDialog("提示：", "正在采集心电数据，请稍等...",
                                    true);
                            mMeasureDialog.show();
                        }
                    }
                case WHAT_CONFIGSUCCESS:
                    // Toast.makeText(MeasureYaXinECG.this, "设备打开成功!",
                    // Toast.LENGTH_SHORT).show();
                    // sendStartNowCmd();
                    break;
                case WHAT_NOFOUNDDEVICE:
                    // Toast.makeText(MeasureYaXinECG.this, "没有找到设备",
                    // Toast.LENGTH_SHORT).show();
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(
                            context);
                    dialogBuilder.setNegativeButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.cancel();
                                }
                            });
                    dialogBuilder.setCancelable(false);
                    dialogBuilder.setTitle("警告！未找到连接的设备！").setMessage(
                            "请检查usb端口连接并重新测量!");
                    AlertDialog dialog = dialogBuilder.create();
                    dialog.setCancelable(false);
                    dialog.show();
                    break;
                case WHAT_OPENDEVICESUCCESS:
                    break;
                case READER_DATA:
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /***
     * 连接成功后设置奥生的指令。实时监控
     */
    private void sendStartNowCmd() {
        connectTV.setText(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS);
        connectTV.setTextColor(Color.BLUE);
        startBtn.setEnabled(true);
        try {
            int writeLength5 = ecgDevice.WriteData(ECGOSenCommand.STARTEcg3,
                    ECGOSenCommand.CheckOK1.length);
            clv = new ControlView(context, sfv, updateUiHandler);
            // clv.setEcgData(ecgData);
            // clv.drawOneBackGround();
            clv.setNowConfig();
//            clv.isStop = true;
            clv.start();
        } catch (IOException e) {
            System.out.println("初始化controlView失败。。。");
            e.printStackTrace();
        }
    }

    //发送停止的命令
    private void sendStopCmd() {
        try {
            if (ecgDevice != null) {
                int writeLength5 = ecgDevice.WriteData(ECGOSenCommand.STOPEcg4,
                        ECGOSenCommand.CheckOK1.length);
            }
        } catch (Exception e) {
            System.out.println("发送停止的命令失败。。。");
            e.printStackTrace();
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.aosheng_ecg12);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        context = this;
        handler = new YaXinHandler();
        initView();
        token = getIntent().getStringExtra("token");
        if (token != null) {
            uploadBtn.setText("获取分析结果");
        }
        setListener();
        // 判断已经连接的标记。
        connectTV.setText("正在连接");
        connectTV.setTextColor(Color.BLUE);
        OpenBeneCheck();
    }

    private static final int AUTOCONN_FAILED = 11;
    private static final int AUTOCONN_SUCCESS = 22;
    public static final int PS_OK = 55;
    public static final int PS_ERROR = 66;

    private void initView() {
        startBtn = (Button) findViewById(R.id.start_btn);
        uploadBtn = (Button) findViewById(R.id.upload_button);
        connectTV = (TextView) findViewById(R.id.connect_status);
        et_xinlv = (EditText) findViewById(R.id.et_xinlv);
        iv_xinlvicon = (ImageView) findViewById(R.id.xinlv_image);
        sfv = (SurfaceView) findViewById(R.id.sfv);
        sfv.setZOrderOnTop(true);
        sfv.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        startBtn.setEnabled(false);
        connectBtn = (Button) findViewById(R.id.aosheng_btn_connect);

    }

    /***
     * 返回一个对象
     *
     * @param title
     * @param message
     * @return
     */
    private AlertDialog showDialog(String title, String message, boolean setOK) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        if (setOK) {
            dialogBuilder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
        }
        dialogBuilder.setCancelable(false);
        dialogBuilder.setTitle(title).setMessage(message);
        AlertDialog dialog = dialogBuilder.create();
        return dialog;
    }

    public void closeAllECG() {
        if (ecgDevice != null) {
            ecgDevice.CloseDevice();
            ecgDevice = null;
        }
        if (clv != null) {
            clv.stop();
            clv = null;
        }
        ControlView.ecgBytesQueue.removeAll();
        ControlView.oneECGQueue.removeAll();
    }

    private boolean isChecked = false;
    private int i = 0;

    private void setListener() {
        clickListener = new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                if (v == startBtn) {
                    measureECGOK = false;
                    if (ecgDevice == null) {
                        return;
                    }
                    try {
//                        ecgDevice.WriteData(
//                                ECGOSenCommand.STOPEcg4,
//                                ECGOSenCommand.CheckOK1.length);
                        ecgDevice.WriteData(ECGOSenCommand.STARTEcg5,
                                ECGOSenCommand.CheckOK1.length);
                        ecgDevice.isNow = false;
                        isStarted = true;
                        // clv.drawFlag=false;
                    } catch (IOException e) {
//                        System.out.println("心电写入数据失败了");
                        e.printStackTrace();
                    }
                    mMeasureDialog = showDialog("提示：", "正在采集心电数据，请稍等...", true);
                    mMeasureDialog.show();
                    startCheckTime = Tools.GetCurrentTime();
                    // startBtn.setEnabled(false);
                    uploadBtn.setEnabled(true);
                    isChecked = true;
                    // 这里是边测量边打印
                    time = Tools.GetCurrentTime() + ".00";
                    time = time.substring(0, 10) + "T"
                            + time.substring(11, time.length());
                    clv.setSavePNGFileName(time);
                    clv.drawFlag = false;
                    pngPath = photoPath = FileSaveUtil.getPrintPath_ECG()
                            + File.separator
                            + BaseActivity.getHealthRecord().getPersonName()
                            + File.separator;
                    pngFileName = time.replace(":", "+") + ".png";
                    photoPath = pngPath + pngFileName;
                } else if (v == uploadBtn) {
                    if (TextUtils.isEmpty(startCheckTime)) {
                        ToastTool.showShort(context, "上传错误，请重新测量！");
                    }
                    if (!measureECGOK) {
                        ToastTool.showLong(context, "请先完成心电测量，再保存数据！");
                        return;
                    }
                    xindian xindian = new xindian();
                    xindian.setIdCard(BaseActivity.getIdCard());
                    xindian.setPicPath(photoPath);
                    xindian.setRhythm(rhythm);
                    if (rhythm.contains("结论")) {
                        String[] results = rhythm.split("结论");
                        if (results != null && results.length == 2) {
                            if (results[1].startsWith("：") || results[1].startsWith(":")) {
                                results[1] = results[1].substring(1);
                            }
                            xindian.setRhythm(results[1].trim());
                        }
                    }
                    xindian.setTime(startCheckTime);
                    boolean b = DBService.add(xindian);
                    uploadSuccess = b;
                    if (b) {
                        ToastTool
                                .showShort(MeasureECGActivity.this, "心电数据保存成功");
                    } else {
                        ToastTool
                                .showShort(MeasureECGActivity.this, "心电数据保存失败");
                    }
                    // uploadECGMeasureData();
                } else if (v == connectBtn) {
                    /*if (MeasureECGActivity.this.connectTV.getText().toString().trim().equals(Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS)) {
                        ToastTool.showShort(context, Contants.Bluetooth_connecting.BLUETOOTH_CONNECTSUCCESS_NOTCONNECTAGAIN);
                        return;
                    }*/
                    if (ecgDevice == null || !ecgDevice.isConnected()) {
                        OpenBeneCheck();
                    }
                }
            }
        };
        startBtn.setOnClickListener(clickListener);
        uploadBtn.setOnClickListener(clickListener);
        connectBtn.setOnClickListener(clickListener);
        // searchBtn.setOnClickListener(clickListener);
    }

    boolean uploadSuccess = false;

    private void uploadECGMeasureData() {
        /** 离线保存 */

        ContentValues cv = new ContentValues();
        // mUploadDialog = showDialog("提示：", "心电数据正在上传，请稍后...", true);
        // mUploadDialog.show();
        uploadInBack(null, null, null);
    }

    /**
     * 图片的地址，用于获取图片保存
     */
    private String photoPath = "";
    private String pngPath = "";
    private String pngFileName = "";

    //点击返回后执行方法
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        sendStopCmd();
        if (!uploadSuccess) {
            try {
                File file = new File(photoPath);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        closeAllECG();
        System.gc();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 查询该用户的的健康体检表，获取身高体重，性别等信息
        // OpenBeneCheck();
    }

    /**
     * 心电测试的结论，心率状况
     */
    private String rhythm = "";
    private CheckBox ecg12_cb_isUpLoad;
    private static final int UPLOAD_RESULT_ZKR = 6666;
    private static final int UPLOAD_RESULT_ZKR_FAILED = 7777;

    private class YaXinHandler extends Handler {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ControlView.DIALOG_FLAG:
                    endCheckTime = Tools.GetCurrentTime();
                    // clv.stop();
                    break;
                case ControlView.PLUS_FLAG:
                    String xinlv = (String) msg.obj;
                    // et_xinlv.setText(xinlv);
                    break;
                case UPLOAD_RESULT:
                    // if (mUploadDialog.isShowing()) {
                    // mUploadDialog.dismiss();
                    // }
                    String code = (String) msg.obj;
                    if ("0".equals(code)) {
                        ToastTool.showShort(context, "远程心电上传成功！");
                        iv_xinlvicon.setImageResource(R.drawable.light_greed);
                        uploadBtn.setEnabled(false);
                    } else {
                        ToastTool.showShort(context, "远程心电上传失败");
                    }
                    break;
                case UPLOAD_RESULT_ZKR:
                    int uploadResult = (int) msg.obj;
                    if (uploadResult == UPLOAD_RESULT_ZKR) {
                        ToastTool.showLong(context, "心电上传成功");
                    } else if (uploadResult == UPLOAD_RESULT_ZKR_FAILED) {
                        ToastTool.showLong(context, "心电上传失败");
                    }
                    break;
                case OFFLINE_RESULT:
                    switch (msg.arg1) {
                        case OFFLINE_OK:
                            ToastTool.showLong(context, "离线保存成功！");
                            break;
                        case OFFLINE_ERROR:
                            ToastTool.showLong(context, "离线保存失败");
                            String item2 = (String) msg.obj;
                            break;
                    }
                    break;
                case OFFLINE_RESULT_OK:
                    ToastTool.showLong(context, "离线保存成功！");
                    break;
                case OFFLINE_RESULT_ERROR:
                    ToastTool.showLong(context, "离线保存错误！");
                    break;
            }
        }
    }

    class User {
        public String getSex() {
            return "男";
        }

        public String getName() {
            return "用户名";
        }
    }

    // AlertDialog mUploadDialog = null;

    @SuppressWarnings("unused")
    @SuppressLint("NewApi")
    protected void upload() throws JSONException {
    }

    public String pdfFileName;
    private String time;
    private AlertDialog mMeasureDialog;
    private AlertDialog.Builder startMeasureDialogBuilder;
    private Button connectBtn;

    public void saveMyBitmap(String bitName, Bitmap mBitmap) {
        String appPath = getApplicationContext().getFilesDir()
                .getAbsolutePath();
        System.out.println(appPath);
        File f = new File("/sdcard/" + bitName + ".png");
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 启用后台线程上传数据
     *
     * @param data
     * @param path
     */
    private void uploadInBack(final JSONObject data, final String path,
                              final ContentValues values) {
        new BackGroundThread(new BackGroundTask() {

            @Override
            public void process() {
                try {
                    upload();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // upload(data, path, values);
            }
        }).start();
    }

}
